package com.kerwin.project.base;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

/**
 * 通用DAO
 * @author KERWIN
 *
 */
@SuppressWarnings("all")
@Repository("projectBaseDao")
public class ProjectBaseDao<T>{
	
	@Resource
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	/**
	 * 保存实体
	 * @param entity
	 * @return
	 */
	public Serializable save(Object entity){
		Serializable serializable = null;
		try {
			serializable = sessionFactory.openSession().save(entity);
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return serializable;
	}
	
	/**
	 * 根据hql语句查询实体
	 * @param hql
	 * @return
	 */
	public List find(String hql){
		return sessionFactory.openSession().createQuery(hql).list();
	}
	
	/**
	 * 根据带占位符参数的hql语句查询实体
	 * @param hql
	 * @param params
	 * @return
	 */
	public List find(String hql, Object...params){
		Query query = sessionFactory.openSession().createQuery(hql);
		for(int i = 0; i < params.length; i++){
			query.setParameter(i + "", params[i]);
		}
		return query.list();
	}
	
	/**
	 * 查询指定数量的数据
	 * @param hql		hql
	 * @param firstNum	起始数据
	 * @param maxNum	数据数量
	 * @param params	参数
	 * @return
	 */
	public List findByLimit(String hql, int firstNum, int maxNum, Object...params){
		Query query = sessionFactory.openSession().createQuery(hql);
		if(null != params && params.length > 0){
			for(int i = 0; i < params.length; i++){
				query.setParameter(i + "", params[i]);
			}
		}
		query.setFirstResult(firstNum);
		query.setMaxResults(maxNum);
		return query.list();
	}
	
	/**
	 * 获取单个实体
	 * @param entityClass	实体类
	 * @param id			实体主键
	 * @return
	 */
	public <T>T get(Class<T> entityClass, Long id){
		return sessionFactory.openSession().get(entityClass, id);
	}
}
